﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgileSaude.Business;
using AgileSaude.Entities;
using System.Reflection;

namespace AgileSaude.Web.Admin
{
    public partial class ListaClinicas : PageBase
    {
        MedicoFacade MedicosFacade = new MedicoFacade();

        private string sortExpression
        {
            get { return ViewState["sortExpression"].ToString(); }
            set { ViewState["sortExpression"] = value; }
        }

        private int sortDirection
        {
            get { return Convert.ToInt32(ViewState["sortDirection"]); }
            set { ViewState["sortDirection"] = value; }
        }

        public int IdMedico
        {
            get { return Convert.ToInt32(ViewState["IdMedico"]); }
            set { ViewState["IdMedico"] = value; }
        }

        public bool ReadOnly
        {
            get { return Convert.ToBoolean(ViewState["ReadOnly"]); }
            set { ViewState["ReadOnly"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Resultado resultado = new Resultado();

                this.sortExpression = "Nome";
                this.sortDirection = 1;

                this.PreencheGrid();
            }
        }

        private void PreencheGrid()
        {
            Resultado resultado = new Resultado();

            List<MedicoEntities> listaMedico = MedicosFacade.ListarClinicas(ref resultado);

            if (resultado.Sucesso)
            {
                ((Label)Master.FindControl("lblMensagem")).Visible = false;
                OrdenarLista(ref listaMedico);
                gvClinicas.DataSource = listaMedico;
                gvClinicas.DataBind();
                gvClinicas.Visible = true;
            }
            else
            {
                gvClinicas.Visible = false;
                ((Label)Master.FindControl("lblMensagem")).Text = resultado.Mensagens[0].Descricoes[0];
                ((Label)Master.FindControl("lblMensagem")).CssClass = "mensagem-vermelho";
                ((Label)Master.FindControl("lblMensagem")).Visible = true;
            }
        }

        private void OrdenarLista(ref List<MedicoEntities> listaMedico)
        {
            listaMedico.Sort(delegate(MedicoEntities a1, MedicoEntities a2)
            {
                Type t = typeof(MedicoEntities);
                PropertyInfo prop = t.GetProperty(sortExpression);
                object u1Value = prop.GetValue(a1, null);
                object u2Value = prop.GetValue(a2, null);
                return ((IComparable)u1Value).CompareTo(((IComparable)u2Value)) * sortDirection;
            });
        }

        protected void gvClinicas_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (sortExpression != e.SortExpression)
                sortDirection = 1; //ASC
            else
                sortDirection *= -1; //DESC

            sortExpression = e.SortExpression;
            PreencheGrid();
        }

        protected void gvClinicas_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Editar":
                    this.ReadOnly = false;
                    this.IdMedico = Convert.ToInt32(gvClinicas.DataKeys[int.Parse(e.CommandArgument.ToString())]["IdMedico"].ToString());
                    Server.Transfer("ClinicaEdit.aspx", false);
                    break;
                case "Visualizar":
                    this.ReadOnly = true;
                    this.IdMedico = Convert.ToInt32(gvClinicas.DataKeys[int.Parse(e.CommandArgument.ToString())]["IdMedico"].ToString());
                    Server.Transfer("ClinicaEdit.aspx", false);
                    break;
                case "Servicos":
                    this.ReadOnly = false;
                    this.IdMedico = Convert.ToInt32(gvClinicas.DataKeys[int.Parse(e.CommandArgument.ToString())]["IdMedico"].ToString());
                    Server.Transfer("ListaServicoClinica.aspx", false);
                    break;
                default:
                    break;
            }
        }

        protected void gvClinicas_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    LinkButton lnkEditar = e.Row.FindControl("lnkEditar") as LinkButton;
                    lnkEditar.CommandArgument = e.Row.RowIndex.ToString();
                    ((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(lnkEditar);

                    LinkButton lnkVisualizar = e.Row.FindControl("lnkVisualizar") as LinkButton;
                    lnkVisualizar.CommandArgument = e.Row.RowIndex.ToString();
                    ((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(lnkVisualizar);

                    LinkButton lnkServicos = e.Row.FindControl("lnkServicos") as LinkButton;
                    lnkServicos.CommandArgument = e.Row.RowIndex.ToString();
                    ((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(lnkServicos);

                    LinkButton imgStatus = e.Row.FindControl("imgStatus") as LinkButton;
                    imgStatus.CommandArgument = e.Row.RowIndex.ToString();

                    if (((MedicoEntities)(e.Row.DataItem)).Ativo == true)
                    {
                        imgStatus.OnClientClick = "return confirm('Deseja realmente inativar?');";
                        //imgStatus.ImageUrl = @"~/Images/bloquear.png";
                        imgStatus.CommandName = "Desativar";
                        imgStatus.ToolTip = "Clique aqui para Inativar a Clínica.";
                        imgStatus.CssClass = "btn btn-acoes";
                        imgStatus.Text = "<i class=\"fa fa-check fa-lg\"></i>";
                    }
                    else
                    {
                        imgStatus.OnClientClick = "return confirm('Deseja realmente ativar?');";
                        //imgStatus.ImageUrl = @"~/Images/bloqueado.png";
                        imgStatus.CommandName = "Ativar";
                        imgStatus.ToolTip = "Clique aqui para Ativar a Clínica.";
                        imgStatus.CssClass = "btn-acoes-danger";
                        imgStatus.Text = "<i class=\"fa fa-times fa-lg\"></i>";
                    }
                }
            }
            catch
            {
                // Response.Redirect("~/sessaoExpirada.aspx", true);
            }
        }

        protected void imgStatus_Click(object sender, EventArgs e)
        {
            Resultado resultado = null;
            LinkButton status = (sender as LinkButton);

            if (status.CommandName == "Ativar")
            {
                resultado = MedicosFacade.Ativar(Int32.Parse(gvClinicas.DataKeys[Int32.Parse(status.CommandArgument)].Value.ToString()));
            }
            else
            {
                resultado = MedicosFacade.Inativar(Int32.Parse(gvClinicas.DataKeys[Int32.Parse(status.CommandArgument)].Value.ToString()));
            }

            string mensagem = string.Empty;

            if (resultado.Sucesso)
            {
                PreencheGrid();
            }

            if (resultado.Mensagens.Count > 0)
            {
                if (resultado.Mensagens[0].Descricoes.Count > 0)
                {
                    mensagem = resultado.Mensagens[0].Descricoes[0].Replace("Médico", "Clínica");
                }
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ResultadoAtualizacao", "alert('" + mensagem + "');", true);

        }

        protected void gvClinicas_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvClinicas.PageIndex = e.NewPageIndex;
            PreencheGrid();
        }

    }
}